

const WorkerThread = require('./worker')
const _workerThread = new WorkerThread()

const {frequency,startTime,savePath,stationCollectionFileName} = require("./config");

const stations = require("./stations.json");

const schedule = require('node-schedule');

const moment = require("moment");
const path = require("path");
const fs = require("fs")
const colors = require("colors")
const os= require("os");
const {checkFileExists} = require("./utils")

let stationsAll = [];

const CreateStationCollection = async()=>{
  return new Promise((resolve, reject)=>{
    const date = moment()

    const _path = path.join(...[
      savePath,
      date.year().toFixed(),
      date.format('YYYY-MM-DD'),
      stationCollectionFileName
    ])
  
    const headers = `stationsID,displayName,city,province,lng,lat,TCDC,PRMSL,QPF,RH,TMP,DPT,VIS,UGRD,VGRD,dateTime`+os.EOL

    checkFileExists(path.join(...[
      savePath,
      date.year().toFixed(),
      date.format('YYYY-MM-DD'),
    ]),true)

    fs.access(_path,fs.constants.F_OK,(err)=>{
      if(err){
        fs.writeFile(_path,headers,(err)=>{
          if(err){
            console.log(colors.red(err))
            return resolve(false)
          }else{
            return resolve(true)
          }
        })
      }else{
        fs.unlinkSync(_path)
        fs.writeFile(_path,headers,(err)=>{
          if(err){
            console.log(colors.red(err))
            return resolve(false)
          }else{
            return resolve(true)
          }
        })
      }
    })

   

   
   })
}

const RunWorker =async ()=>{
  stationsAll= [];
  for (const {stationID,stationName,cityName} of stations) {
    _workerThread.add({stationID:stationID,stationName:stationName,cityName:cityName})
  }
  const status = await CreateStationCollection()
  if(status){
    _workerThread.stop().run()
  }else{
    console.log(colors.red("创建合成文件表头失败"))
  }
}

// TaskPostMessage(function(message){
//   const date = moment()
//   const _path = path.join(...[
//     savePath,
//     date.year().toFixed(),
//     date.format('YYYY-MM-DD'),
//     'stationAll.json'
//   ])
//   fs.appendFile(_path,JSON.stringify(message,"",'\t'),(err)=>{
//     if(err){
//       console.log(`${colors.red("合成站点数据失败,失败原因")}:`)
//     }else{
//       console.log(`${colors.green("合成站点数据成功")}:`)
//     }
//   })
// })


const Task = ()=>{
  console.log(colors.green("定时任务启执行中...."))
  schedule.scheduleJob('0 0 */1 * * *',()=>{
    console.log(colors.green("定时任务执行"+moment().format("YYYY-MM-DD HH:mm:ss")))
    RunWorker();
  })
}

Task();


